/* eslint-disable object-curly-spacing */
/* eslint-disable import/no-unresolved */
/* eslint-disable brace-style */
/* eslint-disable react/no-children-prop */
/* eslint-disable no-constant-condition */
/* eslint-disable no-global-assign */
/* eslint-disable no-mixed-spaces-and-tabs */
/* eslint-disable no-duplicate-imports */
/* eslint-disable import/named */
/* eslint-disable no-unused-vars */
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable no-undef */
import React from 'react';
import {
  View,
  Image,
  Text,
  Platform,
  BackHandler,
  Dimensions,
  StyleSheet,
  TouchableOpacity,
  DeviceEventEmitter,
  ScrollView
} from 'react-native';
import { List } from 'immutable';

import { Device, Service, HostEvent, DarkMode } from "miot";

import { toolbarMarginBottom } from '../Utils/WLStyles';
import { getString } from '../Language/WLLocalizableString';
import CalculateUtils from '../Utils/CalculateUtils';
import ParseProtobuf from '../Utils/WLParseProtobuf';
import Toast from '../View/WLToast';
import SCNet from '../Utils/WLNet';
import { SCDevice } from "../SCNet/SCDevice";
import {
  ZNNOTIFY,
  MIRoomModel,
  GetMapDataType,
  SCCustomPerModel
} from "../SCNet/SCPublic";
import { SCFCManger } from '../SCNet/SCFCManger';

import NavigationBar from "miot/ui/NavigationBar";
import WLNavBar from '../View/WLNavBar';

import InputView from '../View/SetAlertView/WLInputAlertView';
import RenameRoomView from '../View/SetAlertView/WLRenameRoomView';
import MaterialChoiceView from '../View/SetAlertView/WLMaterialChoiceView';

import MapView from '../View/MapView/WLMapView';
import Loading from '../View/WLLoading';
import AlertView from '../View/WLAlertView';
import WLLog from '../Utils/WLLog';
import WLUtils from '../Utils/WLUtils';
import WLConfig from '../Utils/WLConfig';

import {
  ROOM_STATUS,
  HANDLE_TYPE,
  HANDLE_SUCCESS_KEY,
  SPLIT_ROOM_MAX,
  CUSTOM_TYPE,
  MATERIAL_TYPE
} from '../Utils/WLConstant.js';

const { width, height } = Dimensions.get('window');

const LOADING_TYPE = {
  NONE: 0,				// 清空状态
  MAP_DATA: 1,
  MERGE: 2,
  SPLIT: 3,
  RENAME: 4,
  MATERIAL: 5,
  MEMORY_MAP_DATA: 6
};
Object.freeze(LOADING_TYPE);

//  3：成功（美化/拆分/合并）; 4：房间过小； 1000：超时
// 拆分结果  1128
// 3:成功（美化/拆分/合并
// 4:房间过小
// 1000:超时
const SPLITE_RESULT = {
  SUCCESS: 3, // 3:成功
  TOO_SMALL: 4, // 2:房间过小
  TIME_OUT: 1000 // 1000:超时
};

/**
 * 区域编辑
 */
export default class WLEditZonePage extends React.PureComponent {

  constructor() {
    super();

    this.isUnmount = false;
    this.isHandleSuccess = true;

    // 房间拆分的起始点和终点
    this.beginPoint = null;
    this.endPoint = null;

    this.loadingID = LOADING_TYPE.NONE;// 加载组件ID，用于关闭指定操作显示的loading
    this.materialIdx = 0;// 地板材质修改选中的材质idx
    this.getMapType = 0; // 获取地图的类型
    
    // 获取定义的房间类型  [MIRoomModel]
    this.renameList = [];
    this.selectRooms = [];
    this.allRooms = [];
    this.orderList = [];// 预约列表

    this.roomName = '';
    
    // 收到地图变更时的弹框类型
    this.tostMsgType = HANDLE_TYPE.NONE;

    this.mapW = width;
    this.mapH = height;

    this.roomIds = [];
    this.materialID = 0;
    this.relateType = LOADING_TYPE.NONE;// 相关弹窗类型

    this.robotPosition = null;// 机器人位置
    this.standPosition = null;// 充电座位置

    this.state = {
      showInputView: false,
      showRenameView: false,
      showMaterialView: false,
      showRelateAlert: false,
      relateMessage: '',
      showMergeTipAlert: null, // 顺造：是否显示房间合并提示，字段直接记录房间id
      showSplitTipAlert: null, // 顺造：是否显示房间分割提示，字段直接记录房间id

      isDarkMode: DarkMode.getColorScheme() == 'dark', // 是否为暗黑模式

      nameList: List([]),
      renameIdx: 0, // 重命名选中下标
      loading: false,
      showAlert: false,
      
      showSplitDash: false, // 显示分割虚线
      navBarHeight: 0,
      mapRooms: WLConfig.toJSON([]), // List([]),
      mapHeight: this.mapH,
      mapWidth: this.mapW
    };
  }
  componentDidMount() {
    this.listenDeviceCallBack();
    this._handleEditZoneDrawMap();
    
    this._loadMiRooms();
    this.listenNetwork();
  }
  componentWillUnmount() {
    this.isUnmount = true;
    this.hideAllLoading();
    // DarkMode.removeChangeListener((evt) => {});  // 修复地图编辑页返回崩溃
    // ParseProtobuf.clearAllCacheData();
    SCDevice.mapModel.resetPathAndSo();
    this.didFocusListener && this.didFocusListener.remove();
    this.didFocusListener = null;

    this.statusListener && this.statusListener.remove();
    this.statusListener = null;

    this.networkListener && this.networkListener.remove();
    this.networkListener = null;

    if (this.tostMsgType > 0) {
      DeviceEventEmitter.emit(HANDLE_SUCCESS_KEY, { type: this.tostMsgType });
    }
  }
  /**
	 * 显示指定ID的loading
	 * @param {*} ID 
	 */
  showLoadingWithID(ID) {
    if (this.isUnmount) return;
    this.loadingID = ID;
    let interval = (ID == LOADING_TYPE.MERGE || ID == LOADING_TYPE.SPLIT || ID == LOADING_TYPE.RENAME || ID == LOADING_TYPE.MATERIAL) ? 20000 : 8000;
    WLLog.log(`菊花开始:${ new Date().Format("yyyy-MM-dd hh:mm:ss") }`, ID);
    WLUtils.startOutTimer(ID, () => {
      WLLog.log(`菊花超时关闭:${ new Date().Format("yyyy-MM-dd hh:mm:ss") }`, ID);
      this.hideLoadingWithID(ID);
    }, interval);
    this.setState({
      loading: true
    });
  }
  /**
	 * 隐藏指定ID的loading
	 * @param {*} ID 
	 */
  hideLoadingWithID(ID) {
    if (this.isUnmount) return;
    if (ID > 0) {
      setTimeout(() => {
        this.setState({
          loading: false
        });
      }, 100);
      WLLog.log(`菊花关闭:${ new Date().Format("yyyy-MM-dd hh:mm:ss") }`, ID);
      WLUtils.stopOutTimer(ID);
      this.loadingID = LOADING_TYPE.NONE;
      
    }
  }
  hideAllLoading() {
    WLLog.log(`菊花开闭所有${ new Date().Format("yyyy-MM-dd hh:mm:ss") }`);
    this.hideLoadingWithID(this.loadingID);
  }
  // 加载小米的房间列表
  _loadMiRooms = () => {
    Service.room.loadAllRoom(true).then((roomsT) => {
      if (this.isUnmount) return;
      // console.log('小米的房间集合拉取成功:', roomsT);
      let rooms = MIRoomModel.CreateModels(roomsT);
      rooms.push(MIRoomModel.CustomRoom()); // 加入自定义的
      this.renameList = rooms.map((one) => {
        // console.log('FXXK_____one = ',one);
        return { name: one.name, isAdd: false };
      });
      // console.log('小米加载的房间列表数据是:',this.renameList);
      this.setState({
        nameList: List(this.renameList)
      });
    }).catch((error) => {
      this.renameList = [{ name: MIRoomModel.CustomRoom().name, isAdd: false }];
      this.setState({
        nameList: List(this.renameList)
      });
      WLLog.log('小米的房间集合拉取失败:', error);
    });
  }

  _handleDidFocusEvent = () => {
    if (Device.isOnline) {
      this.listenDeviceCallBack();
    }
  }

  /**
   * 监听网络状态
   */
  listenNetwork() {
    this.networkListener = HostEvent.cellPhoneNetworkStateChanged.addListener((event) => {
      const state = Number(event.networkState);
      if (state === 1 || state === 2) { // 1:蜂窝移动 2:wifi
        this._getZoneMemeryMapDataWithoutMapType(this.getMapType);
      }
    });
  }

  /**
   * 监听设备回调
   */
  listenDeviceCallBack() {
    // DarkMode.addChangeListener((value) => {
	  //   // console.log(`colorScheme from listener: ${ value.colorScheme }`);
	  //   this.setState({
    //     isDarkMode: value.colorScheme == 'dark'
    //   });
    // });
    // 监听设备状态回调
    this.statusListener = DeviceEventEmitter.addListener(ZNNOTIFY, (res) => {
      if (this.isUnmount) return;
      WLLog.log("____区域编辑_____回调 res = ", res);
      try {
        const key = res[0];
        const value = res[1];
        if (key == 'S10E1_mapChange') {
          // __DEV__ && WLLog.log("%%%%%%————————地图变更了 S10E1_mapChange");
          this._getZoneMemeryMapData();
        } else if (key == "S2P1_status") {
          // 状态变更为工作中，立即退出当前页
          if (SCDevice.stateModel && SCDevice.stateModel.isWorkState()) {
            // 顺造：返回插件首页，并弹窗提示
            if (SCFCManger.isShunZao()) {
              Toast(getString('zone_edit_robot_working_retry_later'));
              this.props.navigation.navigate('WLHomePage');
            } else {
              this.setState({
                showAlert: true
              });
            }
            // this.props.navigation.goBack();
          }
        } else if (key == "S10E3_arrangeEnd") {
          this._handleSplitFail(value);
        } else if (key == 'BadNetwork') {
          // 网络断开，
          this.tostMsgType = HANDLE_TYPE.NONE;
	      }
      } catch (error) {
        WLLog.log("首页监听回调err = ", error);
      }
    });
  }
  _getOrderList() {
    SCNet.getOrders().then((res) => {
      if (this.isUnmount) return;
      // 非当前图预约排在列表下面
      this.orderList = [];
      for (const ele of res) {
        ele.isDiff = ele.mapID != SCDevice.mapModel.mapId;
        this.orderList.push(ele);

        // if (ele.mapID == SCDevice.mapModel.mapId) {
        //   data.unshift(ele);
        // } else {
        //   // 非当前图
        //   data.push(ele);
        // }
      }
      WLLog.log('获取预约列表 list = ', this.orderList);
    }).catch((err) => {
      if (this.isUnmount) return;
      WLLog.log('获取预约列表 err = ', err);
      WLUtils.showErrToast(err);
    });
  }
  
  /**
   * 修改预约列表开关
   * @param {*} ids 
   */
  _changeOrderInfo(ids) {
    if (this.orderList && this.orderList.length > 0) {
      for (const order of this.orderList) {
        if (!order.isDiff && order.enable && (order.customType == CUSTOM_TYPE.ROOM || order.customType == CUSTOM_TYPE.MANUAL)) {
          const rooms = order.rooms;
          for (const room of rooms) {
            for (const id of ids) {
              if (room.id == id) {
                order.enable = false;
                break;
              }
            }
          }
        }
      }
    }
  }

  _getZoneMemeryMapData() {
    if (this.getMapType == 0) { // 通知来了，5s第一次拉图来图，哪个先来先执行，后面的不处理
      WLLog.log('已经启动拉图了');
      return;
    }
    this._getZoneMemeryMapDataWithoutMapType(this.getMapType);
    this.getMapType = 0;
  }

  /**
   *操作指令下发成功后，拉取一次记忆图
    */
  _getZoneMemeryMapDataWithoutMapType(type) {
    this.isHandleSuccess = true;

    SCNet.getMemoryMapDataBy(type, (result) => {
      if (this.isUnmount) return;
      if (!this.isHandleSuccess) return;
      
      if (result) {
        const allData = ParseProtobuf.getAllData();
        SCDevice.mapModel.resetByAllMapData(allData);

        const mapData = ParseProtobuf.getMapData();
        const mapInfo = ParseProtobuf.getMapInfo();
        const rooms = ParseProtobuf.getMapRooms();
        
        this.allRooms = [];
        for (const room of rooms) {
          this.allRooms.push(Object.assign(room, {}));
        }
        
        this.mapH = mapInfo && mapInfo.sizeY;
        this.mapW = mapInfo && mapInfo.sizeX;
        CalculateUtils.syncMapInfo(mapInfo); // 同步地图信息
        CalculateUtils.syncMapRooms(this.allRooms);
        CalculateUtils.drawMapByMi(mapData).then((base64) => {
          SCNet.loadMapnextStep(8);
          if (this.isUnmount) return;

          this.selectRooms = [];
          this.mapView && this.mapView._clearSelectRoomIds();
          
          this.setState({
            showSplitDash: false,
            mapRooms: WLConfig.toJSON(this.allRooms),
            mapHeight: this.mapH,
            mapWidth: this.mapW
          });
          setTimeout(() => {
            this.mapView && this.mapView._updateMapImage(base64);
            this.mapView && this.mapView._handleChangeChildrenScale();
          }, 0);

          this.hideAllLoading();
          if (this.tostMsgType == HANDLE_TYPE.MERGE) {
            Toast(getString('zone_edit_merge_success'));
          } else if (this.tostMsgType == HANDLE_TYPE.RENAME) {
            Toast(getString('zone_edit_rename_success'));
          } else if (this.tostMsgType == HANDLE_TYPE.CHANGE_MATERIAL) {
            Toast(getString('zone_edit_change_meterial_success'));
            // 材质修改修改，下发同步材质定制性能指令
            this._syncFloorCustomPers();
          }
          SCDevice.mapModel.resetPathAndSo(false); // 编辑地图后，清除地图中的路径
          // this.tostMsgType = HANDLE_TYPE.NONE;
        }).catch((err) => {
          WLUtils.showNetErrToast();
          this.hideAllLoading();
          // this.getMapType = this.getMapType.NONE;
        });
      } else {
        // 拉取失败，复原选中的房间状态 
        this._syncRoomSelectStatus();
        this.setState({
          mapRooms: WLConfig.toJSON(this.allRooms)// List(this.allRooms)
        });
        WLUtils.showNetErrToast();
        this.hideAllLoading();
        // this.getMapType = this.getMapType.NONE;
      }
    });
  }
  /**
   * 同步地板定制性能
   */
  _syncFloorCustomPers() {
    const floorPers = SCDevice.mapModel.customPer.floorPers;// 本地缓存的地板定制
    let pers = [];
    let perIds = [];
    // 取出房间中的材质类型
    if (this.allRooms.length > 0) {
      for (const room of this.allRooms) {
        if ((room.meterialId == MATERIAL_TYPE.CERAMIC_TILE || room.meterialId == MATERIAL_TYPE.WOOD_FLOOR) && perIds.indexOf(room.meterialId) < 0) {
          perIds.push(room.meterialId);
          
          let obj = SCCustomPerModel.DefaultCeramicTilePer;
          if (room.meterialId == MATERIAL_TYPE.WOOD_FLOOR) {
            obj = SCCustomPerModel.DefaultWoodFloorPer;
          }
          pers.push(obj);
          // 同步缓存的地板定制性能参数
          for (const per of floorPers) {
            if (per.id == room.meterialId) {
              obj = per;
              break;
            }
          }
        }
      }
      WLLog.log('发送同步指令 pers = ', pers);
      // 发送同步指令
      SCNet.setCustomSweepType(pers).then((res) => {
        WLLog.log('发送同步指令 res = ', res);
      }).catch((err) => {
        WLUtils.showErrToast(err);
        WLLog.log('发送同步指令 err = ', err);
      });
    }
  }
  /**
   * 同步房间选中状态
   */
  _syncRoomSelectStatus() {
    if (this.selectRooms && this.selectRooms.length > 0) {
      // 全部取消
      for (const room of this.allRooms) {
        room.roomStatus = ROOM_STATUS.NORMAL;
      }
      for (const idx of this.selectRooms) {
        if (idx >= 0) {
          const room = this.allRooms[idx];
          room.roomStatus = ROOM_STATUS.SELECTED;
        }
      }
    } else {
      for (const room of this.allRooms) {
        room.roomStatus = ROOM_STATUS.NORMAL;
      }
    }
  }
  // 处理拆分事件的回调
  _handleSplitFail(value) {
    // 之前的逻辑     4个1时，走旧的逻辑， 5个以上时走新的逻辑
    if (!SCNet.getValueConfig().mapCompareFunc) {
      WLLog.log(`旧协议，0失败，非0等拉图--->${ value }`);
      if (value == 0) {
        let result = SCNet.stopMemeoryMapDataBy(GetMapDataType.change_splite);
        WLLog.log(`_handleEditBack result:${ result }`);
        if (result) {
          this._syncRoomSelectStatus();
          this.setState({
            mapRooms: WLConfig.toJSON(this.allRooms)
          });
          Toast(getString('zone_edit_split_failure'));
          this.hideAllLoading();
        }
      }
    } else {
      WLLog.log(`新协议--->${ value }`);
      // const SPLITE_RESULT = {
      //   SUCCESS: 3,                 // 3:成功
      //   TOO_SMALL: 4,               // 2:房间过小
      //   TIME_OUT: 1000,             // 1000:超时
      // };

      if (SPLITE_RESULT.SUCCESS == value) {
        // 还是等收到拆分成功事件后才提示
        if (this.tostMsgType == HANDLE_TYPE.SPLIT) {
          Toast(getString('zone_edit_split_success'));
        }
        WLLog.log('拆分成功， 如果没拉到图就继续拉图');
        return;
      }
      WLLog.log(`拆分失败，如果在拉图，就停止拉图:${ value }`);
      let result = SCNet.stopMemeoryMapDataBy(GetMapDataType.change_splite);
      if (result) {
        this._syncRoomSelectStatus();
        this.setState({
          mapRooms: WLConfig.toJSON(this.allRooms)
        });
        this.hideAllLoading();
        
        // if (0 == value) {
        //   // 一键撤销成功
        // } else if (1 == value) {
        //   // 吸附失败
        // } else 
        // if (3 == value) {
        //   // 成功(包括美化、拆分、合并) 
        //   let string = getString('zone_edit_split_success');
        //   if (this.tostMsgType == HANDLE_TYPE.MERGE) {
        //     string = getString('zone_edit_merge_success');
        //   }
        //   Toast(string);
        // } else 
        if (SPLITE_RESULT.TOO_SMALL == value) {
          // 房间过小
          Toast(getString('zone_edit_split_failure'));
        } else if (SPLITE_RESULT.TIME_OUT == value) {
          // 超时 1000
          Toast(getString('wall_beauty_timeout'));
        }
        // this.tostMsgType = HANDLE_TYPE.NONE;
      }
    }
  }   
  /**
   * 绘制全图
   */
  _handleEditZoneDrawMap() {
    this.showLoadingWithID(LOADING_TYPE.MAP_DATA);
    setTimeout(() => {
      SCNet.getMemoryMapDataBy(GetMapDataType.current, (result) => {
        if (this.isUnmount) return;
        if (result) {
          // 地图加载成功后，拉取预约列表，防止FDS上传堆积
          this._getOrderList();
          
          const mapData = ParseProtobuf.getMapData();
          const mapInfo = ParseProtobuf.getMapInfo();

          this.mapH = mapInfo && mapInfo.sizeY;
          this.mapW = mapInfo && mapInfo.sizeX;

          const rooms = ParseProtobuf.getMapRooms();
          this.allRooms = [];
          for (const room of rooms) {
            this.allRooms.push(Object.assign(room, {}));
          }
                  
          CalculateUtils.syncMapInfo(mapInfo); // 同步地图信息
          CalculateUtils.syncMapRooms(this.allRooms);
          CalculateUtils.drawMapByMi(mapData).then((base64) => {
            if (this.isUnmount) return;
            this.robotPosition = ParseProtobuf.getRobotPosition();
            this.standPosition = ParseProtobuf.getChargeStationInfo();
            const newRobotPosition = CalculateUtils.getCorrectRobotByChargeStation(this.robotPosition, this.standPosition, true);
            this.mapView && this.mapView._updateRobotPosition(newRobotPosition);
            this.mapView && this.mapView._updateStandPosition(this.standPosition);

            SCNet.loadMapnextStep(8);
            this.setState({
              mapRooms: WLConfig.toJSON(this.allRooms),
              mapHeight: this.mapH,
              mapWidth: this.mapW
            });
            this.mapView && this.mapView._updateMapImage(base64);
            
            this.hideLoadingWithID(LOADING_TYPE.MAP_DATA);
          }).catch((err) => {
            
            WLUtils.showErrToast(err);
            this.hideLoadingWithID(LOADING_TYPE.MAP_DATA);
          });
        } else {
          // 顺造：无地图toast
          if (SCFCManger.isShunZao()) Toast(getString('common_no_map_try_again_later'));
          this.isMapSuccess = false;
          WLUtils.showNetErrToast();
          this.hideLoadingWithID(LOADING_TYPE.MAP_DATA);
        }
      });
    }, 500);
  }

  /**
   * 处理合并点击事件
   */
  _handleMergeEvent() {
    const btnStatus = this._getCurrentBtnHighlightStatus();
    if (this.selectRooms.length != 2||!btnStatus.canMerge) {
      Toast(getString('zone_edit_merge_err_alert'));
      // Toast('请选择两个相邻的房间进行合并');
    } else {
      let ids = [];
      for (const idx of this.selectRooms) {
        if (idx >= 0) {
          const room = this.allRooms[idx];
          ids.push(room.roomId);
        }
      }
      this.roomIds = ids;
      this.relateType = LOADING_TYPE.MERGE;
      WLLog.log('处理合并点击事件 相关预约 ids = ', ids);
      // 顺造：每次都提示 “房间合并后，与该区域相关的定时将失效”
      if (SCFCManger.isShunZao()) {
        this.setState({ showMergeTipAlert: ids });
        return;
      }

      const text = this._checkSplitMergeRelateShowText(ids);
      if (text) {
        this.setState({
          relateMessage: text,
          showRelateAlert: true
        });
        return;
      }
      this._sendMergeCommand(ids);
    }
  }
  // 顺造：房间合并提示
  _renderMergeTipAlert() {
    return !SCFCManger.isShunZao() ? null : (
      <AlertView
        showAlert={!!this.state.showMergeTipAlert}
        message={getString('zone_edit_merge_tip')}
        canDismiss={false}
        onSureFunc={() => {
          const ids = this.state.showMergeTipAlert;
          this._sendMergeCommand(ids);
          setTimeout(() => {
            this.setState({
              showMergeTipAlert: null
            });
          }, 100);
        }}
        onCancelFunc={() => {
          this.setState({
            showMergeTipAlert: null
          });
        }}
      />
    );
  }
  /**
   * 对比预约列表
   * @param {*} ids 
   */
  _checkSplitMergeRelateShowText(ids) {
    try {
      let text = '';
      if (ids.length > 0) {
        // 对比预约列表
        // WLLog.log('对比预约列表  this.orderList = ',this.orderList);
        if (this.orderList.length > 0) {
          let relateCount = 0;
          for (const order of this.orderList) {
            // 当前图的预约 && 预约已打开 &&  判断是否为房间定制、普通清扫预约 
            if (!order.isDiff && order.enable && (order.customType == CUSTOM_TYPE.ROOM || order.customType == CUSTOM_TYPE.MANUAL)) {
              const rooms = order.rooms;
              if (rooms.length > 0) {
                let allIds = [];
                for (const room of rooms) {
                  allIds.push(room.id);
                }
                if (WLUtils.partIncludes(allIds, ids)) {
                  relateCount++;
                }
              }
            }
          }
          WLLog.log('对比预约列表 relateCount = ', relateCount);
          text += WLConfig.getRelateOrderText(relateCount);
        }
        
        // 对比房间定制列表
        const roomPers = SCDevice.mapModel.customPer.roomPers;
        if (roomPers && roomPers.length > 0) {
          let perIds = [];
          for (const per of roomPers) {
            perIds.push(per.id);
          }
          if (WLUtils.partIncludes(perIds, ids)) {
            text += WLConfig.getRelateRoomCustomText(text);
          }
        }
      }
      return text;
    } catch (err) {
      WLLog.log('_____err = ', err);
      return '';
    }
  }
  /**
   * 发送房间合并指令
   * @param {Array} ids 房间id数组
   */
  _sendMergeCommand(ids) {
    if (CalculateUtils.handleRoomMerge(ids)) {
      this.showLoadingWithID(LOADING_TYPE.MERGE);
      // 发送合并指令
      SCNet.mergeRoom(ids).then((res) => {
        if (res.result) {
          this.tostMsgType = HANDLE_TYPE.MERGE;
          this.getMapType = GetMapDataType.change_merge;
          this._getZoneMemeryMapData();
          WLLog.log('房间合并成功后，重新拉取一次预约列表');
          this._changeOrderInfo(ids);// 房间合并成功后，重新拉取一次预约列表
        } else {
          this.hideLoadingWithID(LOADING_TYPE.MERGE);
        }
      }).catch((err) => {
        WLLog.log('合并房间失败 err = ', err);
        WLUtils.showErrToast(err);
        WLUtils.showNetErrToast(err);
        this.hideLoadingWithID(LOADING_TYPE.MERGE);

        // // TODO： 测试
        // this.setState({
        //     showSplitDash: false,
        // });
        // this.tostMsgType = HANDLE_TYPE.MERGE;
        // this.getMapType = GetMapDataType.change_merge;
        // this._getZoneMemeryMapData();
      });   
    } else {
      Toast(getString('zone_edit_merge_err_alert'));
      // Toast('请选择两个相邻的房间进行合并');
    }
  }
  /**
   * 处理拆分点击事件
   */
  _handleSplitEvent() {
    if (this.selectRooms.length != 1) {
      Toast(getString('zone_edit_split_err_alert'));// '请选择一个房间进行分割'
    } else {
      if (this.allRooms.length >= SPLIT_ROOM_MAX) {
        Toast(getString('zone_edit_split_max_alert'));// '单张地图最多支持拆分15个房间'
        return;
      }
      this.setState({
        showSplitDash: true
      });
    }
  }
  /**
   * 处理重命名点击事件
   */
  _handleRenameEvent() {
    WLLog.log('处理重命名点击事件 :', this.selectRooms);
    if (this.selectRooms.length != 1) {
      Toast(getString('zone_edit_rename_err_alert'));
      // Toast('请选择一个房间进行重命名');
    } else {
      const idx = this.selectRooms[0];
      if (idx < 0) {
        return;
      }
      const room = this.allRooms[idx];
      let selectedRoomName = room.roomName;
      
      let index = -1;
      const data = this.state.nameList.toJS();
      for (let j = 0; j < data.length; j++) {
        const element = data[j];
        if (element.name === selectedRoomName) {
          index = j;
          break;
        }
      }
      WLLog.log(`选中的房间名称:${ selectedRoomName }，在列表中的索引:${ index }`);
      
      this.setState({
        renameIdx: index,
        showRenameView: true
      });
    }
  }
  _handleRenameCallback = (name, from) => {
    console.log('房间重命名页面 name = ', name, from);
    this.newName = name;
    this._handleRenameRoomEvent(from);
  }

  /**
   * 处理拆分结果 参数为虚拟世界坐标系 
   * @param {*} begin 开始点坐标 
   * @param {*} end 结束点坐标
   */
  _handleSplitResult(begin, end) {
    // WLLog.log('FXXK______处理拆分结果 begin = ',begin,end);
    if (begin == null || end == null || (begin.x == 0 && begin.y == 0 && end.x == 0 && end.y == 0)) {
      Toast(getString('zone_edit_split_line_err'));// '分割线两端应尽量靠近房间的墙'
      // WLLog.log('分割线两端应尽量靠近房间的墙 22');
      this.beginPoint = null;
      this.endPoint = null;
      return;
    }
    // __DEV__ && WLLog.log(`split result  begin point = (${begin.x} , ${begin.y})  end point = (${end.x} , ${end.y})`);
    // 提交坐标点
    this.beginPoint = begin;
    this.endPoint = end;
  }
  /**
   * 处理保存分割事件
   */
  _hanleSaveSplitEvent() {
    if (this.beginPoint && this.endPoint) {
      try {
        const idx = this.selectRooms[0];
        if (idx < 0) {
          return;
        }
        const room = this.allRooms[idx];
        const roomId = room.roomId;
        
        this.roomIds = [roomId];
        this.relateType = LOADING_TYPE.SPLIT;
        if (SCFCManger.isShunZao()) {
          // 顺造：直接提示
          this.setState({ showSplitTipAlert: roomId});
          return;
        }
        const text = this._checkSplitMergeRelateShowText(this.roomIds);
        if (text) {
          this.setState({
            relateMessage: text,
            showRelateAlert: true
          });
          return;
        }
        this._sendSplitRoomCommand(roomId);
      } catch (err) {
        WLLog.log('拆分失败，err = ', err);
      }
    } else {
      // WLLog.log('分割线两端应尽量靠近房间的墙 111');
      Toast(getString('zone_edit_split_line_err'));// '分割线两端应尽量靠近房间的墙'
    }
  }
  // 顺造：房间分割提示
  _renderSplitTipAlert() {
    return !SCFCManger.isShunZao() ? null : (
      <AlertView
        showAlert={!!this.state.showSplitTipAlert}
        message={getString('zone_edit_split_tip')}
        canDismiss={false}
        onSureFunc={() => {
          const roomId = this.state.showSplitTipAlert;
          this._sendSplitRoomCommand(roomId);
          setTimeout(() => {
            this.setState({
              showSplitTipAlert: null
            });
          }, 100);
        }}
        onCancelFunc={() => {
          this.setState({
            showSplitTipAlert: null
          });
        }}
      />
    );
  }
  /**
   * 发送拆分指令
   * @param {*} roomId 
   */
  _sendSplitRoomCommand(roomId) {
    WLLog.log('发送拆分指令');
    this.showLoadingWithID(LOADING_TYPE.SPLIT);
    SCNet.spliteRoom(roomId, this.beginPoint, this.endPoint).then((res) => {
      if (res.result) {
        this.beginPoint = null;
        this.endPoint = null;
        
        this.setState({
          showSplitDash: false
        });
        this.tostMsgType = HANDLE_TYPE.SPLIT;
        this.getMapType = GetMapDataType.change_splite;
        this._getZoneMemeryMapData();
        WLLog.log('拆分成功后，重新拉取一次预约列表');
        this._changeOrderInfo([roomId]);// 拆分成功后，重新拉取一次预约列表
      } else {
        this.hideLoadingWithID(LOADING_TYPE.SPLIT);
      }
    }).catch((err) => {
      WLLog.log('拆分房间失败 err = ', err);
      WLUtils.showErrToast(err);
      WLUtils.showNetErrToast(err);
      this.hideLoadingWithID(LOADING_TYPE.SPLIT);
      // // TODO： 测试
      // this.setState({
      //     showSplitDash: false,
      // });
      // this.tostMsgType = HANDLE_TYPE.SPLIT;
      // this.getMapType = GetMapDataType.change_splite;
      // this._getZoneMemeryMapData();
    });
  }
  /**
   * 处理重命名确定事件
   * from: 1 自定义  2: 选择的
   */
  _handleRenameRoomEvent(from) {
    if (from == 1) {
      this.setState({
        showInputView: false
      });
    } else if (from == 2) {
      this.setState({
        showRenameView: false
      });
    }
    
    const idx = this.selectRooms[0];
    if (idx < 0) {
      return;
    }
    const room = this.allRooms[idx];
    const roomId = room.roomId;

    // 判断修改后的名称与之前相同，则直接提示修改成功
    if (this.newName == room.roomName) {
      Toast(getString('zone_edit_rename_success'));
      return;
    }


    // 判断不能重名
    let isRepeat = false;
    for (const room of this.allRooms) {
      if (room.roomName == this.newName) {
        isRepeat = true;
        break; 
      }
    }
    if (isRepeat) {
      Toast(getString('zone_edit_name_existed'));
      return;
    }
    
    this.showLoadingWithID(LOADING_TYPE.RENAME);
    SCNet.setRoomName(roomId, this.newName).then((res) => {
      if (res.result) {
        this.tostMsgType = HANDLE_TYPE.RENAME;
        this.getMapType = GetMapDataType.change_rename;
        this._getZoneMemeryMapData();
        if (from == 1) { // 如果是自定义的，需要新建小米的房间
          Service.room.createRoom(this.newName).then((room) => {
            if (room.roomID != undefined) {
              WLLog.log('小米房间创建成功, 重新加载房间列表');
              this._loadMiRooms();
            } else {
              WLLog.log('小米房间创建失败');
            }
          }).catch((error) => {
            WLLog.log('小米创建房间失败 err = ', error);
            WLUtils.showErrToast(error);
            WLUtils.showNetErrToast(err);
          });
        }
      } else {
        this.hideLoadingWithID(LOADING_TYPE.RENAME);
      }
    }).catch((err) => {
      WLLog.log('房间重命名失败 err = ', err);
      WLUtils.showErrToast(err);
      WLUtils.showNetErrToast(err);
      this.hideLoadingWithID(LOADING_TYPE.RENAME);
    });
  }
  /**
   * 修改地板材质
   * cement: 1, // 水泥地面
   * ceramic: 2, // 瓷砖
   * wood: 3, // 木地板
   * others: 30, // 其他
   */
  _handleChangeMaterialEvent() {
    if (this.selectRooms.length == 0) {
      Toast(getString('zone_edit_please_select_room'));// Toast('请先选择房间');
      return;
    }

    if (this.selectRooms && this.selectRooms.length > 0) {
      WLLog.log(`判断设备是否支持同时修改多个房间材质 multiMaterials = ${ SCNet.getValueConfig().multiMaterials }   this.selectRooms = `, this.selectRooms);
      // 判断设备是否支持同时修改多个房间材质
      if (SCNet.getValueConfig().multiMaterials) {
        // 同时设置多个房间材质
        let meterialArray = [];
        for (const idx of this.selectRooms) {
          const room = this.allRooms[idx];
          if (meterialArray.indexOf(room.meterialId) < 0 && (room.meterialId == MATERIAL_TYPE.CERAMIC_TILE || room.meterialId == MATERIAL_TYPE.WOOD_FLOOR)) {
            meterialArray.push(room.meterialId);
          }
        }

        if (meterialArray.length == 1) {
          // 选中的多个房间是同一种材质
          this.materialIdx = meterialArray[0] - 2;
        } else {
          this.materialIdx = -1;
        }
        WLLog.log('同时设置多个房间材质 meterialArray = ', meterialArray, this.materialIdx);
        this.setState({
          showMaterialView: true
        });
      } else {
        if (this.selectRooms.length > 1) {
          Toast(getString('zone_edit_change_meterial_err_alert'));
          // Toast('请选择一个房间修改地板材质');
          return;
        }
        const idx = this.selectRooms[0];
        if (idx < 0) {
          return;
        }
        const room = this.allRooms[idx];
        this.materialIdx = room.meterialId - 2;
        this.setState({
          showMaterialView: true
        });
      }
      return;
    } else {
      Toast(getString('zone_edit_please_select_room'));// Toast('请选择房间');
    }
  }
  /**
   * 选择框点选确定后，发送修改材质命令
   * @param {*} idx 弹窗选中的材质类型
   */
  _handleSaveMaterialEvent = (idx) => {
    try {
      this.setState({
        showMaterialView: false
      });
      // 判断选中的材质是否与当前材质相同
      if (idx == this.materialIdx) {
        return;
      }

      const materialID = idx + 2;
      this.materialID = materialID;
      
      WLLog.log(`选择框点选确定后，发送修改材质命令 multiMaterials = ${ SCNet.getValueConfig().multiMaterials }`);
      // 判断设备是否支持同时修改多个房间材质
      if (SCNet.getValueConfig().multiMaterials) {
        // 同时设置多个房间的材质
        this.roomIds = [];
        for (const ii of this.selectRooms) {
          const room = this.allRooms[ii];
          this.roomIds.push(room.roomId);// 不过滤，发送选中的房间id

          // //相同材质的房间不重复修改
          // if(room.meterialId != materialID){
          //   this.roomIds.push(room.roomId);
          // }
        }
      } else {
        
        const roomIdx = this.selectRooms[0];
        if (roomIdx < 0) {
          return;
        }
        const room = this.allRooms[roomIdx];
        this.roomIds = [room.roomId];
      }
  
      WLLog.log(`同时设置多个房间的材质 materialID = ${ materialID }   roomIds = `, this.roomIds);
      const showText = this._checkMaterialRelateShowText(this.roomIds, materialID);
      if (showText) {
        this.relateType = LOADING_TYPE.CHANGE_MATERIAL;
        this.setState({
          relateMessage: showText,
          showRelateAlert: true
        });
        return;
      }
      this._sendChangeRoomMaterialCommand(this.roomIds, materialID);
    } catch (err) {
      WLLog.log('选择框点选确定后，发送修改材质命令 err = ', err);
    }
  }

  /**
   * 修改材质，获取相关预约显示文案
   * @param {*} ids 房间id数组
   * @param {*} materialID 材质id 
   */
  _checkMaterialRelateShowText(ids, materialID) {
    let relateCount = 0;
    if (this.orderList.length > 0) {
      for (const order of this.orderList) {
        // 判断是否为地板定制预约 && 预约开启 && 非当前图
        if (order.customType == CUSTOM_TYPE.FLOOR && order.enable && !order.isDiff) {
          relateCount++;
        }
      }
      /*
      [{
        "chooseDay": [false, false, true, false, false, false, false], 
        "customType": 0, 
        "day": 4, 
        "enable": false, 
        "hour": 17, 
        "isDiff": true, 
        "isGlobal": false, 
        "mapID": 1606715704, 
        "minute": 56, 
        "orderId": 0, 
        "repeat": false, 
        "rooms": [[SCCOrderRoomPerModel]]
      }]
      */
    }
    return WLConfig.getRelateOrderText(relateCount);
  }
  /**
   * 修改房间材质，修改对应的材质性质预约开关状态
   * @param {*} materialID 
   */
  _changeMaterialOrderInfo(materialID) {
    if (this.orderList && this.orderList.length > 0) {
      for (const order of this.orderList) {
        if (!order.isDiff && order.enable && order.customType == CUSTOM_TYPE.FLOOR) {
          order.enable = false;
          break;
        }
      }
    }
  }
  /**
   * 发送修改材质指令
   * @param {Array} ids 房间id数组
   * @param {Number} materialID 材质id 
   */
  _sendChangeRoomMaterialCommand(ids, materialID) {
    WLLog.log(`发送材质指令  房间ids = ${ ids }   材质id = ${ materialID }`);
    this.showLoadingWithID(LOADING_TYPE.MATERIAL);
    try {
      WLLog.log(`发送材质指令  1`);
      // 判断设备是否支持同时修改多个房间材质
      if (SCNet.getValueConfig().multiMaterials) {
        SCNet.setMoreRoomMaterial(ids, materialID).then((res) => {
          WLLog.log('发送多个房间材质指令 res = ', res);
          if (res) {
            this.tostMsgType = HANDLE_TYPE.CHANGE_MATERIAL;
            this.getMapType = GetMapDataType.change_matriel;
            this._getZoneMemeryMapData();

            this._changeMaterialOrderInfo(materialID);// 修改材质成功后，重新拉取一次预约列表
          } else {
            this.hideLoadingWithID(LOADING_TYPE.MATERIAL);
          }
        }).catch((err) => {
          WLUtils.showErrToast(err);
          this.hideLoadingWithID(LOADING_TYPE.MATERIAL);
          WLLog.log('发送多个房间材质指令 err = ', err);
        });
      } else {
        WLLog.log(`发送材质指令  2`);
        SCNet.setRoomMaterial(ids[0], materialID).then((res) => {
          WLLog.log('发送单个房间材质指令 res = ', res);
          if (res.result) {
            this.tostMsgType = HANDLE_TYPE.CHANGE_MATERIAL;
            this.getMapType = GetMapDataType.change_matriel;
            this._getZoneMemeryMapData();
          } else {
            this.hideLoadingWithID(LOADING_TYPE.MATERIAL);
          }
        }).catch((err) => {
          WLUtils.showErrToast(err);
          this.hideLoadingWithID(LOADING_TYPE.MATERIAL);
          WLLog.log('发送单个房间材质指令 err = ', err);
        });
      }
    } catch (err) {
      WLLog.log('发送材质指令 err = ', err);
      this.hideLoadingWithID(LOADING_TYPE.MATERIAL);
    }
  }
  /**
   * 处理修改材质/拆分/合并操作，相关预约，定制提示弹窗确认事件
   */
  _handleRelateAlertSureEvent() {
    if (this.relateType == LOADING_TYPE.CHANGE_MATERIAL) {
      this._sendChangeRoomMaterialCommand(this.roomIds, this.materialID);
    } else if (this.relateType == LOADING_TYPE.MERGE) {
      this._sendMergeCommand(this.roomIds);
    } else if (this.relateType == LOADING_TYPE.SPLIT) {
      this._sendSplitRoomCommand(this.roomIds[0]);
    }
  }
  /**
   * 处理选择房间事件
   * @param {*} idx 
   * @param {*} roomId 
   * @param {*} roomIds 
   */
  _handleSelectRoomEvent = (idx, roomId, roomIds) => {
    WLLog.log(`选中的房间下标 = ${ idx } 选中的房间id = ${ roomId } 选中的房间id数组 = ${ roomIds }`);
    try {
      const isShunZao = SCFCManger.isShunZao();
      let room = this.allRooms[idx];
      if (room.roomStatus == ROOM_STATUS.NORMAL) {
        room.roomStatus = ROOM_STATUS.SELECTED;
        // 顺造：如果是选中就直接添加，保持选择的顺序，用于房间合并的时候按照先选的房间命名
        if (isShunZao && this.selectRooms.indexOf(idx) === -1) this.selectRooms.push(idx);
      } else {
        room.roomStatus = ROOM_STATUS.NORMAL;
        // 顺造：如果已经选中了，直接删除；注意：需要根据内容去找下标
        if (isShunZao && this.selectRooms.indexOf(idx) > -1) this.selectRooms.splice(this.selectRooms.indexOf(idx), 1);
      }
      
      // 非顺造，还是按照老的方式，先清空，然后再拿数据重新组装
      if (!isShunZao) {
        this.selectRooms = [];
        for (let i = 0; i < this.allRooms.length; i++) {
          const room = this.allRooms[i];
          if (room.roomStatus == ROOM_STATUS.SELECTED) {
            this.selectRooms.push(i);
          }
        }   
      }

      this.setState({
        mapRooms: WLConfig.toJSON(this.allRooms)// List(this.allRooms),
      });
    } catch (err) {

    }
  }

  /**
   * 获取当前状态下底部按钮的状态
   * 返回依次从左到有的按钮的亮起状态的
   */
  
  _getCurrentBtnHighlightStatus() {
    /*
    1）未选中房间
    合并、分割房间、重命名、材质修改，4个按钮均不亮起 
    2）选中1个房间
    合并房间不亮起、重命名亮起、材质修改亮起、分割房间亮起
    3）选中2个房间
    合并房间亮起、分割不亮起，重命名不亮起、材质修改亮起 
    4）选中3个和以上房间
    只材质修改亮起 , { backgroundColor:'red' }
    */
    let result = {
      canMerge: false,
      canSplite: false,
      canRename: false,
      canMeterial: false
    };
    const length = this.selectRooms.length;
    if (length == 1) {
      result.canSplite = true;
      result.canRename = true;
      result.canMeterial = true;
    } else if (length == 2) {
      let roomIDS = [];
      for (const idx of this.selectRooms) {
        if (idx >= 0) {
          const room = this.allRooms[idx];
          roomIDS.push(room.roomId);
        }
      }
      // 选中两个不相邻的房间 合并按钮置灰 0415 暂不支持S1
      if (SCFCManger.is260()||SCFCManger.isShunZao()) {
        if (CalculateUtils.handleRoomMerge(roomIDS)) {
          result.canMerge = true;
        } else {
          result.canMerge = false;
        }
      } else {
        result.canMerge = true;
      }
      result.canMeterial = true;
    } else if (length >= 3) {
      result.canMeterial = true;
    }
    // 不亮起(置灰)的样式  30%不透明度 0217
    result.disabledTextStyle = { opacity: 0.3 };
    return result;
  }

  /**
   * 修改材质：选择了某材质，有关联的预约清扫
   * 拆分/合并：选择了某个房间，有关联的预约清扫
   */
  _renderRelateAlertView() {
    return (
      <AlertView
        showAlert={this.state.showRelateAlert}
        message={this.state.relateMessage}
        onSureFunc={() => {
          this.setState({
            showRelateAlert: false
          });
          this._handleRelateAlertSureEvent();
        }}
        onDismissFunc={() => {
          this.setState({
            showRelateAlert: false
          });
        }}
        onCancelFunc={() => {
          this.setState({
            showRelateAlert: false
          });
        }}
      />
    );
  }
  /**
   * 渲染导航栏
   */
  _renderNavBar() {
    return (
      <WLNavBar
        title={getString('set_zone_edit')}// '区域编辑'
        subtitle=""
        onPressLeftFunc = {() => {
          this.props.navigation.goBack();
        }}
      />
    );
  }
  // 渲染重命名输入框
  _renderRenameDialog() {
    const {
      showInputView
    } = this.state;
    
    return (
      <InputView
        title = {getString('zone_edit_add_name')}
        showAlert = {showInputView}
        showMessage = {false}
        onSureFunc = {(newName) => {
          try {
            if (!newName) {
              Toast(getString('zone_edit_name_not_empty'));
              this.setState({
                showInputView: false
              });
              return;
            }
            let isFind = false;
            const data = this.state.nameList.toJS();
            for (const item of data) {
              if (item.name === newName) {
                isFind = true;
                break;
              }
            }
            if (isFind) {
              this.setState({
                showInputView: false
              });
              if (SCFCManger.isShunZao()) {
                Toast(getString('zone_edit_name_existed'));// 该房间名已存在
              } else {
                Toast(getString('zone_edit_add_name_err_alert'));// 名称不能与其他房间名称相同
              }
              return;
            }
            this.newName = newName;
            
            const listData = this.state.nameList.unshift({ name: newName, isAdd: true });
            this.setState({
              showInputView: false,
              renameIdx: 0,
              nameList: listData
            });
            
            // this._handleRenameRoomEvent(1);
          } catch (error) {
            WLLog.log('InputDialog confirm error:', error);
          }
        }}
        onCancelFunc = {() => {
          this.setState({
            showInputView: false
          });
        }}
      />
    );
  }
  /**
   * 渲染重命名列表
   */
  _renderRenameView() {
    const {
      showRenameView,
      renameIdx,
      nameList
    } = this.state;
    if (!showRenameView) {
      return null;
    }

    return (
      <RenameRoomView
        visible = {showRenameView}
        idx = {renameIdx}
        list = {nameList}
        onCloseFunc = {() => {
          this.setState({
            showRenameView: false
          });
        }}
        onSaveFunc = {(name, from) => {
          this.setState({
            showRenameView: false
          });
          console.log(`FXXK____onSaveFunc name = ${ name }   from = ${ from }`);
          this.newName = name;
          this._handleRenameRoomEvent(from);
        }}
        onShowInputViewFunc = {() => {
          this.setState({
            showInputView: true,
            // showRenameView: false
          });
        }}
      />
    ); 

    // return (
    //   <RenameRoomView
    //     showAlert = {showRenameView}
    //     nameTitles = {this.renameList}
    //     selectedIdx = {renameIdx}
    //     onSureFunc = {(index) => {
    //       if (index == this.renameList.length - 1) {
    //         this.setState({
    //           showRenameView: false,
    //           showInputView: true
    //         });
    //       } else {
    //         WLLog.log(`FFFFFF选中了 用户选中了存在的房间`);
    //         this.newName = this.renameList[index];
    //         this._handleRenameRoomEvent(2);
    //       }
    //     }}
    //     onDismissFunc = {() => {
    //       this.setState({
    //         showRenameView: false
    //       });
    //     }}
    //     onCancelFunc = {() => {
    //       this.setState({
    //         showRenameView: false
    //       });
    //     }}
    //   />
    // );
  }
  /**
   * 渲染材质选择组件
   */
  _renderMaterialView() {
    const {
      showMaterialView
    } = this.state;

    return (
      <MaterialChoiceView
        showAlert = {showMaterialView}
        selectIdx = {this.materialIdx}
        onSureFunc = {(idx) => {
          this._handleSaveMaterialEvent(idx);
        }}
        onDismissFunc = {() => {
          this.setState({
            showMaterialView: false
          });
        }}
        onCancelFunc = {() => {
          this.setState({
            showMaterialView: false
          });
        }}
      />
    );
  }
  /**
   * 渲染底部操作view
   */
  _renderBottomView() {
    const {
      isDarkMode,
      showSplitDash
    } = this.state;
    const btnStatus = this._getCurrentBtnHighlightStatus();
    // 顺造：不显示提示面板
    const showMask = !SCFCManger.isShunZao() && this.selectRooms.length == 0;

    let mergeSource = require('../../resources/images/EditZone/zone_merge_disabled.png');
    if (btnStatus.canMerge) {
      mergeSource = require('../../resources/images/EditZone/zone_merge.png');
    }

    let splitSource = require('../../resources/images/EditZone/zone_split_disabled.png');
    if (btnStatus.canSplite) {
      splitSource = require('../../resources/images/EditZone/zone_split.png');
    }

    let renameSource = require('../../resources/images/EditZone/zone_rename_disabled.png');
    if (btnStatus.canRename) {
      renameSource = require('../../resources/images/EditZone/zone_rename.png');
    }
    let meterialSource = require('../../resources/images/EditZone/zone_material_disabled.png');
    if (btnStatus.canMeterial) {
      meterialSource = require('../../resources/images/EditZone/zone_material.png');
    }

    let closeSource = require('../../resources/images/Common/close.png');
    let completeSource = require('../../resources/images/Common/complete.png');
    if (isDarkMode) {
      closeSource = require('../../resources/images/Common/close_dark.png');
      completeSource = require('../../resources/images/Common/complete_dark.png');
      
      mergeSource = require('../../resources/images/EditZone/zone_merge_dark_disabled.png');
      if (btnStatus.canMerge) {
        mergeSource = require('../../resources/images/EditZone/zone_merge_dark.png');
      }

      splitSource = require('../../resources/images/EditZone/zone_split_dark_disabled.png');
      if (btnStatus.canSplite) {
        splitSource = require('../../resources/images/EditZone/zone_split_dark.png');
      }

      renameSource = require('../../resources/images/EditZone/zone_rename_dark_disabled.png');
      if (btnStatus.canRename) {
        renameSource = require('../../resources/images/EditZone/zone_rename_dark.png');
      }
      meterialSource = require('../../resources/images/EditZone/zone_material_dark_disabled.png');
      if (btnStatus.canMeterial) {
        meterialSource = require('../../resources/images/EditZone/zone_material_dark.png');
      }
    }

    if (showSplitDash) {
      return (
        <View style = {{ backgroundColor: 'white' }}>
          <View style={[styles.bottomView, { justifyContent: 'flex-start' }]}>
            <View style = {{ flexDirection: 'row', alignItems: 'center' }}>
              <TouchableOpacity
                activeOpacity={0.8}
                style={[styles.splitBtn, { marginLeft: 10 }]}
                onPress={() => {
                  this._syncRoomSelectStatus();
                  this.setState({
                    mapRooms: WLConfig.toJSON(this.allRooms), // List(this.allRooms),
                    showSplitDash: false
                  });
                }}
              >
                <Image
                  style={{ width: 40, height: 40 }}
                  source={closeSource}
                />
              </TouchableOpacity>
                            
              <Text style={{ flex: 1, textAlign: 'center', fontSize: WLConfig.getFontSize(14), color: '#333' }}>{getString('zone_edit_split_title')}</Text>

              <TouchableOpacity
                activeOpacity={0.8}
                style={[styles.splitBtn, { marginRight: 10 }]}
                onPress={() => {
                  this._hanleSaveSplitEvent();
                }}
              >
                <Image
                  style={{ width: 40, height: 40 }}
                  source={completeSource}
                />
              </TouchableOpacity>
            </View>
          </View>

          <View style = {{ height: WLUtils.isIphoneX() ? 12 : 0 }}/>
        </View>
      );
    }
    return (
      <View style = {{ backgroundColor: 'white' }}> 
        <View style={styles.bottomView}>
          <TouchableOpacity
            activeOpacity={0.7}
            style={styles.bottomBtn}
            onPress={() => {
              // 让用户可以点击  ---- 0218
              // if(!btnStatus.canMerge) return;
              WLLog.log('埋点··············点击了合并按钮');
              this._handleMergeEvent();
            }}
          >
            <Image
              style={styles.bottomBtnImg}
              source={mergeSource}
            />
            <Text style={[styles.bottomBtnTxt,
              btnStatus.canMerge ? {} : btnStatus.disabledTextStyle]}>{getString('zone_edit_merge')}</Text>
          </TouchableOpacity>

          <TouchableOpacity
            activeOpacity={0.7}
            style={styles.bottomBtn}
            onPress={() => {
              // 让用户可以点击  ---- 0218
              // if(!btnStatus.canSplite) return;
              WLLog.log('埋点··············点击了拆分按钮');
              this._handleSplitEvent();
            }}
          >
            <Image
              style={styles.bottomBtnImg}
              source={splitSource}
            />
            <Text style={[styles.bottomBtnTxt,
              btnStatus.canSplite ? {} : btnStatus.disabledTextStyle]}>{getString('zone_edit_split')}</Text>
          </TouchableOpacity>
          
          <TouchableOpacity
            activeOpacity={0.7}
            style={styles.bottomBtn}
            onPress={() => {
              // 让用户可以点击  ---- 0218
              // if(!btnStatus.canRename) return;
              WLLog.log('埋点··············点击了重命名按钮');
              this._handleRenameEvent();
            }}
          >
            <Image
              style={styles.bottomBtnImg}
              source={renameSource}
            />
            <Text style={[styles.bottomBtnTxt,
              btnStatus.canRename ? {} : btnStatus.disabledTextStyle]}>{getString('zone_edit_rename')}</Text>
          </TouchableOpacity>

          { SCFCManger.hasCustomFloor ? 
            <TouchableOpacity
              activeOpacity={0.7}
              style={styles.bottomBtn}
              onPress={() => {
                // 让用户可以点击  ---- 0218
                // if(!btnStatus.canMeterial) return;
                WLLog.log('埋点··············点击了修改材质按钮');
                this._handleChangeMaterialEvent();
              }}
            >
              <Image
                style={styles.bottomBtnImg}
                source={meterialSource}
              />
              <Text style={[styles.bottomBtnTxt,
                btnStatus.canMeterial ? {} : btnStatus.disabledTextStyle]}>{getString('zone_edit_change_meterial')}</Text>
            </TouchableOpacity> : null
          }
        </View>
        {
          showMask ?
            <View style={styles.maskView}>
              <Text style={styles.maskText}>{ getString('zone_edit_none_select_room') }</Text>
            </View> : null
        }
        
        <View style = {{ height: WLUtils.isIphoneX() ? 12 : 0 }}/>
      </View>
    );
  }
  _renderAlertView() {
    return (
      <AlertView
        showAlert={this.state.showAlert}
        canDismiss={false}
        btnTexts={[getString('common_determine')]}
        message={WLConfig.getDeviceWorkText()}
        onCancelFunc={() => {
          this.setState({
            showAlert: false
          });
          setTimeout(() => {
            this.props.navigation.goBack();
          }, 100);
        }}
      />
    );
  }
  render() {
    const {
      navBarHeight,
      mapWidth,
      mapHeight,
      mapRooms,

      loading,
      showAlert,
      showSplitDash
    } = this.state;

    return (
      <View style={[styles.container]}>
        {this._renderNavBar()}

        <View
          style={{ flex: 1 }}
          onLayout={(evt) => {
            const nativeEvent = evt.nativeEvent;
            this.setState({
              navBarHeight: nativeEvent.layout.y
            });
          }}
        >
          <MapView
            ref={(mapView) => { this.mapView = mapView; }}
            specifyRate = {0.618}
            mapMarginBottom = {83}
            navBarHeight={navBarHeight}
            mapWidth={mapWidth}
            mapHeight={mapHeight}
            imageCount={20}
            rooms={mapRooms}
            canEditRoom={!showSplitDash}
            splitDashStatus={showSplitDash ? 0 : -1}
            onSplitRoomFunc={(begin, end) => {
              this._handleSplitResult(begin, end);
            }}
            onSelectRoomFunc={(idx, id, roomIds) => {
              this._handleSelectRoomEvent(idx, id, roomIds);
            }}
          />
          {/* 底部操作 */}
          {this._renderBottomView()}
        </View>
        <Loading isShow={loading} navHeight={navBarHeight} />
          
        {this._renderAlertView()}
        {this._renderRenameView()}
        {this._renderRenameDialog()}
        {this._renderMaterialView()}
        {this._renderRelateAlertView()}
        {this._renderMergeTipAlert()}
        {this._renderSplitTipAlert()}
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    // backgroundColor: 'rgb(240,240,240)'
    backgroundColor: 'white'
  },
  bottomView: {
    height: 83,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'white',
    justifyContent: 'space-evenly'
  },
  maskView: {
    backgroundColor: 'white',
    position: 'absolute',
    left: 0,
    top: 0,
    right: 0,
    height: 83,
    alignItems: 'center',
    justifyContent: 'center'
  },
  maskText: {
    textAlign: 'center',
    fontWeight: 'bold',
    fontFamily: WLConfig.getLanTing(),
    fontSize: WLConfig.getFontSize(14),
    color: '#333333',
    lineHeight: WLConfig.getLineHeight(19)
  },
  bottomBtn: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
    // marginBottom: toolbarMarginBottom
  },
  bottomBtnImg: {
    width: 20,
    height: 20
  },
  bottomBtnTxt: {
    fontSize: WLConfig.getFontSize(12),
    fontFamily: WLConfig.getLanTing(),
    fontWeight: 'bold',
    marginTop: 8,
    color: '#333'
  },
  splitBtn: {
    padding: 10,
    justifyContent: 'center',
    alignContent: 'center'
  },
  choiceDialogScrollView: {
    height: 400
    // backgroundColor: 'red'
  }
});